package edu.ucsd.cse110;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import edu.ucsd.cse110.model.Log;

/**
 * Displays a graph of body weight progression.
 */
public class BodyWeightGraph {
	/**
	 * Creates the graph of body weight progression.
	 */
	public Intent getIntent(Context context) {
		Format formatter = new SimpleDateFormat("dd-MMM-yy");

		// Gets all log entries.
		LocalDatabaseManager database = new LocalDatabaseManager(context);
		List<Log> logs = database.getAllLog();
		database.close();

		// Returns null if no entry is found.
		if (logs.size() == 0) {
			return null;
		}

		TimeSeries series = new TimeSeries("Body Weight Progression");

		for (int i = 0; i < logs.size(); i++) {
			if (logs.get(i).getBodyWeight() > 0) {
				// Add data to the graph series
				series.add(i, logs.get(i).getBodyWeight());
			}
		}

		// Sets up the graph.
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		dataset.addSeries(series);

		XYSeriesRenderer renderer = new XYSeriesRenderer();
		renderer.setColor(Color.WHITE);
		renderer.setPointStyle(PointStyle.CIRCLE);
		renderer.setFillPoints(true);
		renderer.setChartValuesTextSize(25);
		renderer.setGradientEnabled(true);
		renderer.setDisplayChartValues(true);

		XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer);
		mRenderer.setChartTitleTextSize(30);
		mRenderer.setBackgroundColor(Color.WHITE);
		mRenderer.setShowGrid(true);
		mRenderer.setGridColor(Color.GRAY);
		mRenderer.setXTitle("Date");
		mRenderer.setYTitle("Weight (lbs)");
		mRenderer.setZoomButtonsVisible(true);
		mRenderer.setXLabels(0);

		// Enters data into the graph.
		for (int i = 0; i < logs.size(); i++) {
			mRenderer.addXTextLabel(i,
					formatter.format(logs.get(i).getDate().getTime()));
		}
		mRenderer.setBarSpacing(20);

		Intent intent = ChartFactory.getLineChartIntent(context, dataset,
				mRenderer, "Body Weight Progression");

		return intent;

	}
}
